<template>
  <div class="json-formatter-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <div class="title-with-back">
          <el-button 
            type="primary" 
            :icon="ArrowLeft" 
            @click="$router.push('/tools')"
            class="blue-return-button"
            circle
          />
          <div class="title-content">
            <div class="title-main">
              <el-icon class="title-icon"><Document /></el-icon>
              <h2>JSON格式化</h2>
            </div>
            <p class="page-description">
              <el-icon><Document /></el-icon>
              <span>JSON数据格式化、压缩、验证工具，支持语法高亮、代码折叠、自动格式化、特殊字符转义、保存文件</span>
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- JSON 状态提示 -->
    <el-alert 
      v-if="jsonStatus.message" 
      :title="jsonStatus.message" 
      :type="jsonStatus.type" 
      :closable="false"
      class="status-alert"
      :class="{ 'fullscreen-alert': isFullscreen }"
    />

    <!-- Monaco Editor 编辑器区域 - 左右对比 -->
    <el-card class="editor-card" :class="{ 'fullscreen-editor': isFullscreen }">
      <template #header>
        <div class="editor-card-header">
          <!-- 区域标识 -->
          <div class="editor-labels">
            <div class="editor-label">
              <el-icon><Edit /></el-icon>
              <span>输入区</span>
            </div>
            <div class="editor-divider-vertical"></div>
            <div class="editor-label">
              <el-icon><View /></el-icon>
              <span>输出区</span>
            </div>
          </div>
          
          <!-- 功能操作按钮 -->
          <div class="toolbar-actions">
            <el-button type="primary" @click="formatJson" :icon="Check" size="small">格式化</el-button>
            <el-button type="warning" @click="compressJson" :icon="Fold" size="small">压缩</el-button>
            <el-button type="success" @click="copyJson" :icon="DocumentCopy" size="small">复制</el-button>
            <el-button type="info" @click="saveJson" :icon="Download" size="small">保存</el-button>
            <el-button @click="toggleFold" :icon="isFolded ? Expand : Fold" size="small">
              {{ isFolded ? '展开' : '折叠' }}
            </el-button>
            
            <el-divider direction="vertical" />
            
            <div class="toolbar-item">
              <span class="toolbar-label">转义</span>
              <el-switch v-model="escapeMode" @change="onEscapeModeChange" size="small" />
            </div>
            <div class="toolbar-item">
              <span class="toolbar-label">行号</span>
              <el-switch v-model="showLineNumbers" @change="toggleLineNumbers" size="small" />
            </div>
            
            <el-divider direction="vertical" />
            
            <el-button 
              :type="isFullscreen ? 'danger' : ''" 
              @click="toggleFullscreen" 
              :icon="isFullscreen ? CloseBold : FullScreen"
              size="small"
            >
              {{ isFullscreen ? '退出全屏' : '全屏' }}
            </el-button>
          </div>
        </div>
      </template>
      <div class="editors-wrapper">
        <div class="editor-panel">
          <div ref="editorContainerLeft" class="editor-container"></div>
        </div>
        <div class="editor-divider"></div>
        <div class="editor-panel">
          <div ref="editorContainerRight" class="editor-container"></div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  ArrowLeft, Document, DocumentCopy, Check, Fold, Expand, 
  FullScreen, CloseBold, Edit, View, Download
} from '@element-plus/icons-vue'
import * as monaco from 'monaco-editor'
import { copyToClipboard as copyText } from '@/utils/clipboard'

// 配置 Monaco Editor 环境
self.MonacoEnvironment = {
  getWorker(_, label) {
    if (label === 'json') {
      return new Worker(new URL('monaco-editor/esm/vs/language/json/json.worker.js', import.meta.url), { type: 'module' })
    }
    return new Worker(new URL('monaco-editor/esm/vs/editor/editor.worker.js', import.meta.url), { type: 'module' })
  }
}

// 编辑器实例
const editorContainerLeft = ref(null)
const editorContainerRight = ref(null)
let editorLeft = null
let editorRight = null

// 状态
const showLineNumbers = ref(true)
const escapeMode = ref(false)
const isFolded = ref(false)
const isFullscreen = ref(false)
const jsonStatus = ref({
  message: '',
  type: 'info'
})
let statusTimer = null
let formatTimer = null

// ESC 键处理函数
const handleEsc = (e) => {
  if (e.key === 'Escape' && isFullscreen.value) {
    toggleFullscreen()
  }
}

// 初始化编辑器
onMounted(() => {
  // 左侧编辑器（输入区）
  if (editorContainerLeft.value) {
    editorLeft = monaco.editor.create(editorContainerLeft.value, {
      value: '',
      language: 'json',
      theme: 'vs',
      automaticLayout: true,
      minimap: {
        enabled: false
      },
      fontSize: 14,
      lineNumbers: 'on',
      scrollBeyondLastLine: false,
      wordWrap: 'on',
      folding: true,
      foldingStrategy: 'indentation',
      renderLineHighlight: 'all',
      selectOnLineNumbers: true,
      roundedSelection: false,
      readOnly: false,
      cursorStyle: 'line',
      contextmenu: false, // 禁用右键菜单
    })

    // 监听内容变化
    editorLeft.onDidChangeModelContent(() => {
      validateJson()
      autoFormatJson()
    })

    // 同步滚动
    editorLeft.onDidScrollChange(() => {
      if (editorRight) {
        const leftScroll = editorLeft.getScrollTop()
        editorRight.setScrollTop(leftScroll)
      }
    })
  }

  // 右侧编辑器（输出区）
  if (editorContainerRight.value) {
    editorRight = monaco.editor.create(editorContainerRight.value, {
      value: '',
      language: 'json',
      theme: 'vs',
      automaticLayout: true,
      minimap: {
        enabled: false
      },
      fontSize: 14,
      lineNumbers: 'on',
      scrollBeyondLastLine: false,
      wordWrap: 'on',
      folding: true,
      foldingStrategy: 'indentation',
      renderLineHighlight: 'all',
      selectOnLineNumbers: true,
      roundedSelection: false,
      readOnly: true, // 右侧只读
      cursorStyle: 'line',
      contextmenu: false, // 禁用右键菜单
    })

    // 同步滚动
    editorRight.onDidScrollChange(() => {
      if (editorLeft) {
        const rightScroll = editorRight.getScrollTop()
        editorLeft.setScrollTop(rightScroll)
      }
    })
  }

  // 监听 ESC 键退出全屏
  window.addEventListener('keydown', handleEsc)
})

// 清理
onUnmounted(() => {
  if (editorLeft) {
    editorLeft.dispose()
  }
  if (editorRight) {
    editorRight.dispose()
  }
  if (statusTimer) {
    clearTimeout(statusTimer)
  }
  if (formatTimer) {
    clearTimeout(formatTimer)
  }
  window.removeEventListener('keydown', handleEsc)
  document.body.style.overflow = ''
})

// 验证 JSON
const validateJson = () => {
  if (!editorLeft) return false
  
  // 清除之前的定时器
  if (statusTimer) {
    clearTimeout(statusTimer)
    statusTimer = null
  }
  
  let value = editorLeft.getValue().trim()
  
  if (!value) {
    jsonStatus.value = {
      message: '',
      type: 'info'
    }
    return false
  }

  try {
    let parseValue = value
    
    // 默认模式：智能处理
    if (!escapeMode.value) {
      // 尝试1：可能输入的是 JSON 字符串
      try {
        const firstParse = JSON.parse(value)
        if (typeof firstParse === 'string') {
          const unescaped = unescapeSpecialChars(firstParse)
          JSON.parse(unescaped)
          parseValue = unescaped
        } else {
          parseValue = value
        }
      } catch {
        // 尝试2：直接去转义
        try {
          const unescaped = unescapeSpecialChars(value)
          JSON.parse(unescaped)
          parseValue = unescaped
        } catch {
          parseValue = value
        }
      }
    }
    
    JSON.parse(parseValue)
    // JSON 格式正确时，不显示状态提示（只在操作时弹出消息通知）
    jsonStatus.value = {
      message: '',
      type: 'info'
    }
    return true
  } catch (error) {
    // 只在格式错误时显示提示
    jsonStatus.value = {
      message: `JSON 格式错误: ${error.message}`,
      type: 'error'
    }
    return false
  }
}

// 去转义（将转义序列还原为原始字符）
// 用于处理输入中的转义字符（如 \n, \t, \" 等）
const unescapeSpecialChars = (str) => {
  return str
    .replace(/\\u003c/g, '<')
    .replace(/\\u003e/g, '>')
    .replace(/\\u0026/g, '&')
    .replace(/\\n/g, '\n')
    .replace(/\\r/g, '\r')
    .replace(/\\t/g, '\t')
    .replace(/\\b/g, '\b')
    .replace(/\\f/g, '\f')
    .replace(/\\"/g, '"')
    .replace(/\\\\/g, '\\')
}

// 自动格式化 JSON（带防抖）
const autoFormatJson = () => {
  // 清除之前的定时器
  if (formatTimer) {
    clearTimeout(formatTimer)
  }
  
  // 500ms 防抖
  formatTimer = setTimeout(() => {
    if (!editorLeft || !editorRight) return
    
    let value = editorLeft.getValue().trim()
    
    if (!value) {
      editorRight.setValue('')
      return
    }

    try {
      let parseValue = value
      
      // 智能处理：尝试多种输入格式
      // 尝试1：可能输入的是 JSON 字符串 "{\n \"name\": ...}"
      try {
        const firstParse = JSON.parse(value)
        // 如果解析出来是字符串，说明是 JSON 字符串
        if (typeof firstParse === 'string') {
          // 对这个字符串内容去转义，然后再解析
          const unescaped = unescapeSpecialChars(firstParse)
          JSON.parse(unescaped) // 测试是否能解析
          parseValue = unescaped
        } else {
          // 解析出来是对象，直接使用
          parseValue = value
        }
      } catch {
        // 尝试2：直接去转义（输入本身带转义但没有外层引号）
        try {
          const unescaped = unescapeSpecialChars(value)
          JSON.parse(unescaped)
          parseValue = unescaped
        } catch {
          // 都失败，使用原值
          parseValue = value
        }
      }
      
      const parsed = JSON.parse(parseValue)
      let formatted = JSON.stringify(parsed, null, 2)
      
      // 转义模式：将格式化的 JSON 再次 stringify 成 JSON 字符串
      if (escapeMode.value) {
        formatted = JSON.stringify(formatted)
      }
      
      editorRight.setValue(formatted)
    } catch (error) {
      // 自动格式化失败时不显示错误消息
      // 用户可以继续输入
    }
  }, 500)
}

// 手动格式化 JSON
const formatJson = () => {
  if (!editorLeft || !editorRight) return
  
  let value = editorLeft.getValue().trim()
  
  if (!value) {
    ElMessage.warning('请输入 JSON 数据')
    return
  }

  try {
    let parseValue = value
    
    // 智能处理
    // 尝试1：可能输入的是 JSON 字符串
    try {
      const firstParse = JSON.parse(value)
      if (typeof firstParse === 'string') {
        const unescaped = unescapeSpecialChars(firstParse)
        JSON.parse(unescaped)
        parseValue = unescaped
      } else {
        parseValue = value
      }
    } catch {
      // 尝试2：直接去转义
      try {
        const unescaped = unescapeSpecialChars(value)
        JSON.parse(unescaped)
        parseValue = unescaped
      } catch {
        parseValue = value
      }
    }
    
    const parsed = JSON.parse(parseValue)
    let formatted = JSON.stringify(parsed, null, 2)
    
    // 转义模式：将格式化的 JSON 再次 stringify 成 JSON 字符串
    if (escapeMode.value) {
      formatted = JSON.stringify(formatted)
    }
    
    editorRight.setValue(formatted)
    ElMessage.success('格式化成功')
  } catch (error) {
    ElMessage.error(`格式化失败: ${error.message}`)
  }
}

// 压缩 JSON
const compressJson = () => {
  if (!editorLeft || !editorRight) return
  
  let value = editorLeft.getValue().trim()
  
  if (!value) {
    ElMessage.warning('请输入 JSON 数据')
    return
  }

  try {
    let parseValue = value
    
    // 智能处理
    // 尝试1：可能输入的是 JSON 字符串
    try {
      const firstParse = JSON.parse(value)
      if (typeof firstParse === 'string') {
        const unescaped = unescapeSpecialChars(firstParse)
        JSON.parse(unescaped)
        parseValue = unescaped
      } else {
        parseValue = value
      }
    } catch {
      // 尝试2：直接去转义
      try {
        const unescaped = unescapeSpecialChars(value)
        JSON.parse(unescaped)
        parseValue = unescaped
      } catch {
        parseValue = value
      }
    }
    
    const parsed = JSON.parse(parseValue)
    let compressed = JSON.stringify(parsed)
    
    // 转义模式：将压缩的 JSON 再次 stringify 成 JSON 字符串
    if (escapeMode.value) {
      compressed = JSON.stringify(compressed)
    }
    
    editorRight.setValue(compressed)
    ElMessage.success('压缩成功')
  } catch (error) {
    ElMessage.error(`压缩失败: ${error.message}`)
  }
}

// 复制 JSON
const copyJson = () => {
  if (!editorRight) return
  
  const value = editorRight.getValue().trim()
  
  if (!value) {
    ElMessage.warning('没有可复制的内容')
    return
  }

  copyText(value, 'JSON内容')
}

// 保存 JSON 文件
const saveJson = () => {
  if (!editorRight) return
  
  let value = editorRight.getValue().trim()
  
  if (!value) {
    ElMessage.warning('没有可保存的内容')
    return
  }

  try {
    let parseValue = value
    
    // 智能处理：始终尝试去转义以保存标准 JSON
    // 尝试1：可能是 JSON 字符串
    try {
      const firstParse = JSON.parse(value)
      if (typeof firstParse === 'string') {
        const unescaped = unescapeSpecialChars(firstParse)
        JSON.parse(unescaped)
        parseValue = unescaped
      } else {
        parseValue = value
      }
    } catch {
      // 尝试2：直接去转义
      try {
        const unescaped = unescapeSpecialChars(value)
        JSON.parse(unescaped)
        parseValue = unescaped
      } catch {
        parseValue = value
      }
    }
    
    // 验证 JSON 格式
    const parsed = JSON.parse(parseValue)
    // 重新格式化为标准 JSON（确保格式正确）
    const standardJson = JSON.stringify(parsed, null, 2)
    
    // 创建 Blob 对象
    const blob = new Blob([standardJson], { type: 'application/json;charset=utf-8' })
    
    // 生成文件名（带时间戳）
    const date = new Date()
    const timestamp = date.toISOString().replace(/[:.]/g, '-').slice(0, -5)
    const filename = `formatted-${timestamp}.json`
    
    // 创建下载链接
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    
    // 清理
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    ElMessage.success(`已保存为 ${filename}`)
  } catch (error) {
    ElMessage.error('JSON 格式错误，无法保存')
  }
}

// 切换折叠
const toggleFold = () => {
  if (!editorLeft || !editorRight) return
  
  if (isFolded.value) {
    editorLeft.getAction('editor.unfoldAll').run()
    editorRight.getAction('editor.unfoldAll').run()
    isFolded.value = false
    ElMessage.success('已展开全部')
  } else {
    editorLeft.getAction('editor.foldAll').run()
    editorRight.getAction('editor.foldAll').run()
    isFolded.value = true
    ElMessage.success('已折叠全部')
  }
}

// 切换行号
const toggleLineNumbers = () => {
  if (!editorLeft || !editorRight) return
  
  const lineNumbersOption = showLineNumbers.value ? 'on' : 'off'
  editorLeft.updateOptions({
    lineNumbers: lineNumbersOption
  })
  editorRight.updateOptions({
    lineNumbers: lineNumbersOption
  })
}

// 转义模式变化
const onEscapeModeChange = (value) => {
  if (value) {
    ElMessage.info('已开启转义：输出 JSON 字符串（带转义字符 \\n, \\t, \\" 等）')
  } else {
    ElMessage.info('已关闭转义：输出标准格式化的 JSON')
  }
  
  // 重新格式化以应用转义设置
  autoFormatJson()
}

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
  
  if (isFullscreen.value) {
    document.body.style.overflow = 'hidden'
    ElMessage.success('已进入全屏模式')
  } else {
    document.body.style.overflow = ''
    ElMessage.success('已退出全屏模式')
  }
}
</script>

<style scoped>
.json-formatter-container {
  padding: 0;
  min-height: calc(100vh - 60px);
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.page-title {
  flex: 1;
}

.title-with-back {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.blue-return-button {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
  flex-shrink: 0;
  margin-top: 2px;
}

.blue-return-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.4);
  background: linear-gradient(135deg, #66b3ff 0%, #409eff 100%);
}

.title-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.title-main {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 28px;
  color: #409eff;
}

.title-content h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
  margin: 8px 0 0 0;
  padding: 8px 12px;
  background: #f0f9ff;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.page-description .el-icon {
  color: #409eff;
  font-size: 16px;
}

/* 工具栏项 */
.toolbar-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 10px;
  background: #f5f7fa;
  border-radius: 6px;
}

.toolbar-label {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
}

/* 状态提示 */
.status-alert {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.status-alert :deep(.el-alert__content) {
  display: flex;
  align-items: center;
  font-weight: 500;
}

/* 编辑器卡片 */
.editor-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.editor-card :deep(.el-card__header) {
  padding: 14px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8f0fe 100%);
  border-bottom: 2px solid #409eff;
}

.editor-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
}

/* 区域标识 */
.editor-labels {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-shrink: 0;
}

.editor-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.editor-label .el-icon {
  font-size: 18px;
  color: #409eff;
}

.editor-divider-vertical {
  width: 2px;
  height: 24px;
  background: linear-gradient(180deg, #409eff 0%, #66b3ff 100%);
  border-radius: 1px;
}

/* 工具栏按钮 */
.toolbar-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.toolbar-actions .el-button {
  border-radius: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.toolbar-actions .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 8px rgba(64, 158, 255, 0.2);
}

.toolbar-actions .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border: none;
}

.toolbar-actions .el-button--warning {
  background: linear-gradient(135deg, #e6a23c 0%, #f0b864 100%);
  border: none;
}

.toolbar-actions .el-button--success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border: none;
}

.toolbar-actions .el-button--danger {
  background: linear-gradient(135deg, #f56c6c 0%, #f89898 100%);
  border: none;
}

.toolbar-actions .el-button--info {
  background: linear-gradient(135deg, #909399 0%, #b1b3b8 100%);
  border: none;
}

.toolbar-actions .el-divider--vertical {
  margin: 0 4px;
  height: 20px;
}

/* 双编辑器容器 */
.editors-wrapper {
  display: flex;
  gap: 0;
  width: 100%;
  height: 600px;
}

.editor-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.editor-divider {
  width: 4px;
  background: linear-gradient(180deg, #409eff 0%, #66b3ff 100%);
  flex-shrink: 0;
}

.editor-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

/* 全屏样式 */
.fullscreen-alert {
  position: fixed;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  width: auto;
  max-width: 600px;
  min-width: 300px;
  z-index: 10001;
  margin: 0;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.fullscreen-editor {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9998;
  margin: 0;
  border-radius: 0;
  background: #ffffff;
}

.fullscreen-editor :deep(.el-card__header) {
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.fullscreen-editor .editors-wrapper {
  height: calc(100vh - 75px);
}

.fullscreen-editor .editor-container {
  height: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .editor-card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .toolbar-actions {
    width: 100%;
    justify-content: flex-start;
  }
}

@media (max-width: 768px) {
  .editor-labels {
    width: 100%;
    justify-content: center;
  }

  .editor-divider-vertical {
    width: 100%;
    height: 2px;
  }

  .toolbar-actions {
    width: 100%;
    justify-content: center;
  }

  .editors-wrapper {
    flex-direction: column;
    height: 800px;
  }

  .editor-panel {
    flex: 1;
  }

  .editor-divider {
    width: 100%;
    height: 4px;
  }

  .editor-container {
    height: 100%;
  }
  
  .fullscreen-editor .editors-wrapper {
    height: calc(100vh - 140px);
  }
}
</style>

